import { Button, Select, Space } from "antd";
import { useEffect, useState } from "react";
import { optionsRequest } from "./service";
import "@/tailwind-variables.less";

export interface Option {
  label: string;
  value: any;
}

const convertDataToSelect = (
  array: any[],
  labelKey: string,
  valueKey: string
) => {
  return array.map((item) => ({
    label: item[labelKey],
    value: item[valueKey],
  }));
};

// 计算下拉框正确的值，根据接口返回的数据，如果找到，返回当前值，没找到返回默认值
const computeSelectValue = ({
  currentValue,
  options,
  defaultValue = "",
}: {
  currentValue: any;
  options: any[];
  defaultValue: any;
}) => {
  // 遍历选项数组，如果没找到，初始为第一个
  const findIndex = options.findIndex((i) => i.value === currentValue);
  console.log("findIndex:", findIndex);
  const defaultIndex = options.findIndex((i) => i.value === defaultValue);
  console.log("defaultIndex:", defaultIndex);
  if (findIndex === -1) {
    defaultValue = defaultIndex === -1 ? "" : options[defaultIndex].value;
    return defaultValue;
  } else {
    return currentValue;
  }
};

export const SelectState = () => {
  const [createValue, setCreateValue] = useState();
  const [editValue, setEditValue] = useState();
  const [options, setOptions] = useState<Option[]>([]);
  const mount = async () => {
    const res = await optionsRequest();
    // 数据转换
    const _options = convertDataToSelect(res, "name", "value");
    setOptions(_options);
  };
  useEffect(() => {
    mount();
    return () => {};
  }, []);

  const selectChange = (value: any) => {
    // 做一些操作
    console.log("selectChange ~ value:", value);
    setCreateValue(value);
  };

  const writeBackTest = () => {
    setEditValue(
      computeSelectValue({
        currentValue: createValue,
        options: options.slice(0, options.length - 1),
        defaultValue: "001",
      })
    );
  };

  return (
    <div>
      <Space direction="vertical" className="w-80">
        <div className="flex justify-between">
          新建状态
          <Select
            className="w-56"
            value={createValue}
            options={options}
            onChange={selectChange}
          />
        </div>
        <div className="flex justify-between">
          <Button onClick={writeBackTest}>回写测试</Button>
          <Select
            className="w-56"
            value={editValue}
            options={options.slice(0, options.length - 1)}
            onChange={selectChange}
          />
        </div>
      </Space>
    </div>
  );
};
